# Delete existing files
if (Test-Path electron-preload.js) {
    Remove-Item electron-preload.js -Force
    Write-Host "Deleted electron-preload.js"
}

if (Test-Path electron-preload.cjs) {
    Remove-Item electron-preload.cjs -Force
    Write-Host "Deleted electron-preload.cjs"
}

# Compile TypeScript file
Write-Host "Compiling electron-preload.ts"
tsc electron-preload.ts --outDir . --esModuleInterop --module CommonJS

# Check compilation success
if ($LASTEXITCODE -eq 0) {
    Write-Host "Compilation successful"
    
    # Check if .js file was generated
    if (Test-Path electron-preload.js) {
        Write-Host "Found electron-preload.js, renaming..."
        # Rename the file
        Rename-Item -Path electron-preload.js -NewName electron-preload.cjs -Force
        Write-Host "Renamed successfully"
        
        # Verify the file was created
        if (Test-Path electron-preload.cjs) {
            Write-Host "Successfully created electron-preload.cjs file"
            Get-Item electron-preload.cjs | Format-Table Name, Length, LastWriteTime
        } else {
            Write-Host "Error: Could not find electron-preload.cjs after renaming"
            exit 1
        }
    } else {
        Write-Host "Error: Could not find electron-preload.js after compilation"
        exit 1
    }
} else {
    Write-Host "Compilation failed with exit code: $LASTEXITCODE"
    exit 1
}